<?php
/**
 * Created by PhpStorm.
 * User: zws
 * Date: 2018/9/8
 * Time: 11:02
 * 检测人员管理
 */
namespace app\api\service;

use app\common\model\ImageModel;
use app\common\model\MachineModel;
use app\common\model\OperateModel;
use app\common\model\OrderModel;
use app\common\model\ProtectModel;
use app\common\model\ReportModel;
use app\common\model\TemplateModel;
use think\Db;
use think\Log;

class ReportService
{
    protected static $reportModel;
    protected static $imageModel;
    protected static $operateModel;
    protected static $protectModel;
    protected static $machineModel;
    protected static $templateModel;
    protected static $orderModel;
    protected $type;

    /**
     * ReportService constructor.
     * @param ReportModel $reportModel
     * @param ImageModel $imageModel
     * @param ProtectModel $protectModel
     * @param MachineModel $machineModel
     * @param TemplateModel $templateModel
     * @param OrderModel $orderModel
     * @param OperateModel $operateModel
     */
    public function __construct(ReportModel $reportModel,
                                ImageModel $imageModel,
                                ProtectModel $protectModel,
                                MachineModel $machineModel,
                                TemplateModel $templateModel,
                                OrderModel $orderModel,
                                OperateModel $operateModel)
    {
        self::$reportModel = $reportModel;
        self::$imageModel = $imageModel;
        self::$operateModel = $operateModel;
        self::$protectModel = $protectModel;
        self::$machineModel = $machineModel;
        self::$templateModel = $templateModel;
        self::$orderModel = $orderModel;
        $this->type = 3;
    }

    public function createAll($params)
    {
        if (empty($params)) {
            return app_fail(9997);
        }

        // 检测数据是单条还是多条
        if (!is_array($params['res_code'])) {
            return app_fail(9975);
        }

        // 拼装数据
        $data = [];
        foreach ($params['res_code'] as $key => $val) {
            $data[] = [
                'report_name'  => empty($params['report_name'][$key]) ? '' : $params['report_name'][$key],
                'res_code'     => $val,
                'machine_code' => empty($params['machine_code'][$key]) ? '' : $params['machine_code'][$key],
                'report_proto' => empty($params['report_proto'][$key]) ? '' : $params['report_proto'][$key],
                'template_id'  => empty($params['template_id'][$key]) ? '' : $params['template_id'][$key],
                'proto_json'   => empty($params['proto_json'][$key]) ? '' : $params['proto_json'][$key],
                'user_id'      => empty($params['tokenId']) ? 1 : $params['tokenId'],
                'remark'       => '',
                'create_time'  => time(),
                'update_time'  => time(),
                'image'        => empty($params['image']['name'][$key]) ? '' : $params['image'],
            ];
        }
       
        // 图片保存目录
        $path = config('param_config.imagePath');
        $report_id = [];
        // 开启事务
        Db::startTrans();
        $time = time();
        $report_url = 'http://'.$_SERVER['HTTP_HOST'].'/report_info?id=';
        $return_data = [];
        try {
            // 需要返回每次插入的 id 只能单条插入
            foreach ($data as $key => $value) {
                // 插入报告
                $report = self::$reportModel->create([
                    'report_name'  => $value['report_name'],
                    'res_code'     => $value['res_code'],
                    'machine_code' => $value['machine_code'],
                    'report_proto' => $value['report_proto'],
                    'template_id'  => $value['template_id'],
                    'proto_json'   => $value['proto_json'],
                    'user_id'      => $value['user_id'],
                    'remark'       => '',
                    'create_time'  => $value['create_time'],
                    'update_time'  => $value['create_time'],
                ]);
                $report_id[] = $report->id;
                $return_data[] = [
                    'report_id' => $report->id,
                    'date' => date('Y-m-d H:i:s', $time),
                    'url' => $report_url.$report->id
                ];
                // 添加报告图片流
                if (isset($params['image']['name'][$key]) && count($params['image']['name'][$key]) > 0) {
                    $fileData = [];
                    foreach ($params['image']['name'][$key] as $k => $file) {
                        $ext = strrchr($file,'.');
                        $info = $path . md5(time() + mt_rand(100, 999)) . $ext;
                        if (move_uploaded_file($value['image']['tmp_name'][$key][$k], $info)) {
                            $fileData[] = [
                                'report_id' => $report->id,
                                'img_url' => $info,
                                'user_id' => $value['user_id'],
                                'create_time' => time(),
                                'update_time' => time()
                            ];
                        }
                    }
                    self::$imageModel->saveAll($fileData);
                }
                // 报告操作记录表
                $operate_data = self::$operateModel->where(['res_code' =>$value['res_code'],
                    'user_id'=>$value['user_id'], 'machine_code'=>$value['machine_code']])->find();
                if(!$operate_data) {
                    self::$operateModel->save([
                        'res_code' => $value['res_code'],
                        'machine_code' => $value['machine_code'],
                        'user_id' => $value['user_id'],
                        'create_time' => time(),
                        'update_time' => time()
                    ]);
                }
            }
            Db::commit();

            return $return_data;
        } catch (\Exception $e) {
            dump($e->getMessage());
            die;
            Db::rollback();
            return app_fail(9996);
        }
    }

    /**
     * 注册用户上传报告
     * User: zhouyao
     * Date: 2018/11/27
     * Time: 9:38 PM
     * @param $params
     * @return mixed
     * @throws \app\common\exception\AppException
     */
    public function create($params)
    {
        if (empty($params) || !isset($params['tokenId'])) {
            return app_fail(9997);
        }
        if(!isset($params['res_code']) || empty($params['res_code']))
        {
            app_fail(8599);
        }
        if(!isset($params['machine_code']) || empty($params['machine_code']))
        {
            app_fail(8299);
        }
        if(!isset($params['template_id']) || empty($params['template_id']))
        {
            app_fail(8594);
        }
        if(!isset($params['report_name']) || empty($params['report_name']))
        {
            app_fail(8587);
        }
        if(!isset($params['report_proto']) || empty($params['report_proto']))
        {
            app_fail(8586);
        }
        if(!isset($params['proto_json']) || empty($params['proto_json']))
        {
            app_fail(8585);
        }
        $time = time();
        $data = [
            'report_name'  => $params['report_name'],
            'res_code'     => $params['res_code'],
            'machine_code' => $params['machine_code'],
            'report_proto' => $params['report_proto'],
            'template_id'  => $params['template_id'],
            'user_id'      => $params['tokenId'],
//            'order_id'     => $params['order_id'],
            'proto_json'     => $params['proto_json'],
            'remark'       => '',
            'create_time'  => $time,
            'update_time'  => $time
        ];
        $path = config('param_config.imagePath');
        Db::startTrans();

        try {
            // 添加报告
            $report = self::$reportModel->create($data);
            // 添加报告图片流
            if (isset($params['image']) && count($params['image']) > 0) {
                $data = [];
                foreach ($params['image'] as $key => $file) {
                    $info = $file->validate(['size' => 4096000, 'ext' => 'jpg,png,gif,jpeg'])->move($path);
                    if ($info) {
                        $data[] = [
                            'report_id' => $report->id,
                            'img_url' => $info->getSaveName(),
                            'user_id' => $params['tokenId'],
                            'create_time' => $time,
                            'update_time' => $time
                        ];
                    }
                }
                self::$imageModel->saveAll($data);
            }
            // 报告操作记录表
            $operate_data = self::$operateModel->where(['res_code'=>$params['res_code'],
                'user_id'=>$params['tokenId'], 'machine_code'=>$params['machine_code']])->find();
            if(!$operate_data) {
                self::$operateModel->save([
                    'res_code' => $params['res_code'],
                    'machine_code' => $params['machine_code'],
                    'user_id' => $params['tokenId'],
                    'create_time' => $time,
                    'update_time' => $time
                ]);
            }
            Db::commit();
            return [
                'report_id' => $report->id,
                'date' => date('Y-m-d H:i:s', $time),
                'url' => 'http://'.$_SERVER['HTTP_HOST'].'/report_info?id='.$report->id
            ];
        } catch (\Exception $e) {
            Db::rollback();
            return app_fail(9996);
        }
    }

    /**
     * 报告列表下载
     * User: zhouyao
     * Date: 2018/11/28
     * Time: 3:16 PM
     * @param $params
     * @return array
     * @throws \app\common\exception\AppException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index($params)
    {
        if (empty($params) || !isset($params['tokenId'])) {
            return app_fail(9997);
        }
        if(!isset($params['page'])){
            $params['page'] = 1;
        }
        if(!isset($params['limit'])){
            $params['limit'] = 20;
        }
        $where = ['user_id' => $params['tokenId']];
        $count = self::$reportModel->where($where)->count();
        if ($count < 1) {
            return ['count' => $count, 'links' => [], 'type' => 0];
        }

        // 获取数据
        $page = is_int($params['page']) ? $params['page'] < 1 ? 1 : $params['page'] : 1;
        $limit = is_int($params['limit']) ? $params['limit'] > 50 ? 50 : $params['limit'] : 20;
        if($params['page'] > 0)
        {
            $result = self::$reportModel->where($where)
                ->page($page, $limit)
                ->select();
        }else{
            $result = self::$reportModel->where($where)
                ->select();
        }
        $result_arr = $result->toArray();

        $res_codes = array_column($result_arr, 'res_code');
        $machine_codes = array_column($result_arr, 'machine_code');
        if($result)
        {
            $res_datas = $this->get_protect($res_codes);
            $machine_datas = $this->get_machine($machine_codes);
            foreach ($result as $k=>$v)
            {
                $datas[$k] = array(
                    'id'=>$v['id'],
                    'name'=>$v['report_name'],
                    'res_code'=>$v['res_code'],
                    'machine_code'=>$v['machine_code'],
                    'template_id'=>$v['template_id'],
                    'proto'=>$v['report_proto'],
                    'res_name'=>isset($res_datas[$v['res_code']]) ? $res_datas[$v['res_code']] : '',
                    'machine_name'=>isset($machine_datas[$v['machine_code']]) ? $machine_datas[$v['machine_code']] : '',
                    'date' => $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '',
                    'url' => 'http://'.$_SERVER['HTTP_HOST'].'/report_info?id='.$v['id'],    //
                    // TODO 此处需要转 proto 的数据做成页面展示
                );

            }
        }

        // TODO 此处需要转 proto 的数据做成页面展示

        return ['count' => $count, 'links' => $datas, 'type' => 0];
    }

    public function show($params)
    {
        if (empty($params) || !isset($params['code']) || !isset($params['machine_type']) || !isset($params['page_type'])) {
            return app_fail(9997);
        }
        if(empty($params['code']))
        {
            app_fail(8584);
        }
        if($params['page_type'] == 1)
        {
            //获取历史报告
            return $this->get_report($params);
        }else{
            //获取模板
            return $this->get_template($params);
        }

    }

    /**
     * zws
     * 获取报告
     * @param $params
     * @return array
     */
    public function get_report($params)
    {
        if($params['machine_type'] == 1)
        {
            //测试仪
            $where[] = ['machine_code', 'in' , $params['code']];
            $machine_data = self::$machineModel->where(['machine_code'=>$params['code']])
                ->find();
            if(!$machine_data)
            {
                //测试仪器不存在
                app_fail(8298);
            }
        }else{
            //保护
            $where[] = ['res_code', 'in' , $params['code']];
            $res_data = self::$protectModel->where(['res_code'=>$params['code']])->find();
            if(empty($res_data))
            {
                app_fail(8595);
            }
        }
        $count = self::$reportModel->where($where)
            ->count();
        if ($count < 1) {
            return ['links' => [], 'count' => $count, 'type' => $params['page_type']];
        }
        if(!isset($params['page']) || empty($params['page'])){
            $params['page'] = 1;
        }
        if(!isset($params['limit']) || empty($params['limit'])){
            $params['limit'] = 20;
        }
        if($params['page'] > 0)
        {
            $result = self::$reportModel->where($where)
                ->page($params['page'], $params['limit'])
                ->order('create_time', 'desc')
                ->select();
        }else
        {
            $result = self::$reportModel->where($where)
                ->order('create_time', 'desc')
                ->select();
        }
        $datas = [];
        if($result)
        {
            $res_codes = [];
            $machine_codes = [];
            foreach ($result as $v)
            {
                $res_codes[] = $v['res_code'];
                $machine_codes[] = $v['machine_code'];
            }
            $res_datas = $this->get_protect($res_codes);
            $machine_datas = $this->get_machine($machine_codes);
            foreach ($result as $k=>$v)
            {
                $datas[$k] = array(
                    'id'=>$v['id'],
                    'name'=>$v['report_name'],
                    'res_code'=>$v['res_code'],
                    'machine_code'=>$v['machine_code'],
                    'template_id'=>$v['template_id'],
                    'proto'=>$v['report_proto'],
                    'res_name'=>isset($res_datas[$v['res_code']]) ? $res_datas[$v['res_code']] : '',
                    'machine_name'=>isset($machine_datas[$v['machine_code']]) ? $machine_datas[$v['machine_code']] : '',
                    'date' => $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '',
                    'url' => 'http://'.$_SERVER['HTTP_HOST'].'/report_info?id='.$v['id'],    //
                    // TODO 此处需要转 proto 的数据做成页面展示
                );

            }
        }
        return ['links' => $datas, 'count' => $count, 'type' => $params['page_type']];
    }

    /**
     * zws
     * 获取模板
     * @param $params
     * @return array
     */
    public function get_template($params)
    {
        if($params['machine_type'] == 1)
        {
            //测试仪无模板
            app_fail(9997);
        }
        $res_data = self::$protectModel->where(['res_code'=>$params['code']])->find();
        if(empty($res_data))
        {
            app_fail(8595);
        }
        //保护
        $where[] = ['res_code', 'in' , $params['code']];
        $count = self::$templateModel->where($where)
            ->count();
        if ($count < 1) {
            return ['links' => [], 'count' => $count, 'type' => $params['page_type']];
        }
        if(!isset($params['page']) || empty($params['page'])){
            $params['page'] = 1;
        }
        if(!isset($params['limit']) || empty($params['limit'])){
            $params['limit'] = 20;
        }
        if($params['page'] > 0)
        {
            $result = self::$templateModel->where($where)
                ->page($params['page'], $params['limit'])
                ->order('create_time', 'desc')
                ->select();
        }else
        {
            $result = self::$templateModel->where($where)
                ->order('create_time', 'desc')
                ->select();
        }
        $datas = [];
        if($result)
        {
            $res_codes = [];
            $template_ids = [];
            foreach ($result as $v)
            {
                $res_codes[] = $v['res_code'];
                $template_ids[] = $v['id'];
            }
            $res_datas = $this->get_protect($res_codes);
            $template_img_datas = $this->get_template_img($template_ids);
            foreach ($result as $k=>$v)
            {
                $datas[$k] = array(
                    'id'=>$v['id'],
                    'name'=>$v['template_name'],
                    'res_code'=>$v['res_code'],
                    'machine_code'=>'',
                    'template_id'=>'',
                    'proto'=>$v['template_proto'],
                    'res_name'=>isset($res_datas[$v['res_code']]) ? $res_datas[$v['res_code']] : '',
                    'machine_name'=>'',
                    'date' => $v['create_time'] ? date('Y-m-d H:i:s', $v['create_time']) : '',
                    'url' => '',
                    'imgs' => isset($template_img_datas[$v['id']]) ?
                        $template_img_datas[$v['id']] : []
                );

            }
        }
        return ['links' => $datas, 'count' => $count, 'type' => $params['page_type']];
    }

    /**
     * zws
     * 获取保护名称
     * @param $res_codes
     * @return array
     */
    public function get_protect($res_codes)
    {
        if(empty($res_codes) || !is_array($res_codes))
        {
            return [];
        }
        $where = [['res_code', 'in', $res_codes]];
        $datas = [];
        $result = self::$protectModel->where($where)->select();
        if($result)
        {
            foreach ($result as $v)
            {
                $datas[$v['res_code']] = $v['res_name'];
            }
        }
        return $datas;
    }

    /**
     * zws
     * 获取测试仪名称
     * @param $machine_codes
     * @return array
     */
    public function get_machine($machine_codes)
    {
        if(empty($machine_codes) || !is_array($machine_codes))
        {
            return [];
        }
        $where = [['machine_code', 'in', $machine_codes]];
        $datas = [];
        $result = self::$machineModel->where($where)->select();
        if($result)
        {
            foreach ($result as $v)
            {
                $datas[$v['machine_code']] = $v['machine_name'];
            }
        }
        return $datas;
    }

    /**
     * 获取模板图片
     * @param $template_ids
     * @return array
     */
    public function get_template_img($template_ids)
    {
        if(empty($template_ids) || !is_array($template_ids))
        {
            return [];
        }
        $where = [['template_id', 'in', $template_ids]];
        $datas = [];
        $result = self::$imageModel->where($where)->select();
        $path = config('param_config.imagePath');
        $filePath = config('app.app_host').substr($path, 1);
        if($result)
        {
            foreach ($result as $v)
            {
                $datas[$v['template_id']][] = [
                    'path'=>$v['path'],
                    'img_url'=>$v['img_url'] ? $filePath.$v['img_url'] : ''
                ];
            }
        }
        return $datas;
    }

    /**
     * zws
     * 上传工单报告，工单结束
     * @param $params
     * @return bool|void
     */
    public function upload_report($params)
    {
        if (empty($params) || !isset($params['tokenId'])) {
            return app_fail(9997);
        }
        if(!isset($params['res_code']) || empty($params['res_code']))
        {
            app_fail(8599);
        }
        if(!isset($params['machine_code']) || empty($params['machine_code']))
        {
            app_fail(8299);
        }
        if(!isset($params['work_id']) || empty($params['work_id']))
        {
            app_fail(6996);
        }
        if(!isset($params['report_name']) || empty($params['report_name']))
        {
            app_fail(8587);
        }
        if(!isset($params['report_proto']) || empty($params['report_proto']))
        {
            app_fail(8586);
        }
        if(!isset($params['proto_json']) || empty($params['proto_json']))
        {
            app_fail(8585);
        }
        $order_data = self::$orderModel->where(['id'=>$params['work_id']])->find();
        if(empty($order_data))
        {
            app_fail(6999);
        }
        $params['template_id'] = $order_data['template_id'];
        $data = [
            'report_name'  => $params['report_name'],
            'res_code'     => $params['res_code'],
            'machine_code' => $params['machine_code'],
            'report_proto' => $params['report_proto'],
            'template_id'  => $params['template_id'],
            'user_id'      => $params['tokenId'],
            'order_id'     => $params['work_id'],
            'proto_json'     => $params['proto_json'],
            'remark'       => '',
            'create_time'  => time(),
            'update_time'  => time()
        ];
        $path = config('param_config.imagePath');
        Db::startTrans();

        try {
            // 添加报告
            $report = self::$reportModel->create($data);
            // 添加报告图片流
            if (count($params['image']) > 0) {
                $data = [];
                foreach ($params['image'] as $key => $file) {
                    $info = $file->validate(['size' => 4096000, 'ext' => 'jpg,png,gif,jpeg'])->move($path);
                    if ($info) {
                        $data[] = [
                            'report_id' => $report->id,
                            'img_url' => $info->getSaveName(),
                            'user_id' => $params['tokenId'],
                            'create_time' => time(),
                            'update_time' => time()
                        ];
                    }
                }
                self::$imageModel->saveAll($data);
            }

//            // 报告操作记录表
//            $operate_data = self::$operateModel->where(['res_code'=>$params['res_code'],
//                'user_id'=>$params['tokenId'], 'machine_code'=>$params['machine_code']])->find();
//            if(!$operate_data) {
//                self::$operateModel->save([
//                    'res_code' => $params['res_code'],
//                    'machine_code' => $params['machine_code'],
//                    'user_id' => $params['tokenId'],
//                    'create_time' => time(),
//                    'update_time' => time()
//                ]);
//            }
            $update_data = ['status'=>2, 'finish_date'=>time()];
            self::$orderModel->where(['id'=>$params['work_id']])->update($update_data);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            return app_fail(9996);
        }
    }


}